﻿using WXWorkSvc.Common.Extensions;
using WXWorkSvc.Common.Models;

namespace WXWorkSvc.Models;

public class WXWorkPrivate
{

    private readonly string _CorpId;
    private readonly HttpClient _HC;
    private readonly IHttpContextAccessor _Accessor;
    private readonly ILogger<WXWorkPrivate> _Logger;
    private readonly IServiceProvider _ServiceProvider;
    public WXWorkPrivate(HttpClient hc, IConfiguration configuration, IHttpContextAccessor acc, ILogger<WXWorkPrivate> logger, IServiceProvider provider)
    {
        _CorpId = configuration["WXWork:CorpId"]!;
        _HC = hc;
        _HC.BaseAddress = new Uri("https://qyapi.weixin.qq.com");
        _Accessor = acc;
        _Logger = logger;
        _ServiceProvider = provider;
    }


    public async Task SendTextMessageAsync(int agentId, string? userIds, string message)
    {
        if (string.IsNullOrEmpty(userIds))
            return;
        if (userIds.Split('|').Where(ii => !string.IsNullOrEmpty(ii)).Count() == 0)
            return;

        await _HC.PostAsJsonAsync($"cgi-bin/message/send?access_token={await GetAccessTokenAsync(agentId)}", new
        {
            touser = userIds,
            agentid = agentId,
            msgtype = "text",
            text = new
            {
                content = message
            }
        });
    }
    /// <summary>
    /// 
    /// </summary>
    /// <param name="userIds">指定接收消息的成员，成员ID列表（多个接收者用‘|’分隔，最多支持1000个）。    特殊情况：指定为"@all"，则向该企业应用的全部成员发送</param>
    /// <param name="message">markdown内容，最长不超过2048个字节，必须是utf8编码</param>
    /// <returns></returns>
    public async Task SendMDMessageAsync(int agentId, string? userIds, string message)
    {

        if (string.IsNullOrEmpty(userIds))
            return;
        if (userIds.Split('|').Where(ii => !string.IsNullOrEmpty(ii)).Count() == 0)
            return;


        await _HC.PostAsJsonAsync($"cgi-bin/message/send?access_token={await GetAccessTokenAsync(agentId)}", new
        {
            touser = userIds,
            agentid = agentId,
            msgtype = "markdown",
            markdown = new
            {
                content = message
            }
        });
    }




    private async Task<string> GetAccessTokenAsync(int agentId)
    {
        using var db = getdb();
        var item = await db.PrivateAgents.FindAsync(agentId);
        if (item!.DTExpiresToken < DateTime.Now)
        {

            var ret = await _HC.GetFromJsonAsync<ResponseAccessToken>($"cgi-bin/gettoken?corpid={_CorpId}&corpsecret={item.Secret}");
            ret.Valid();
            item.Token = ret!.access_token;
            item.DTExpiresToken = DateTime.Now.AddSeconds(ret.expires_in);
            await db.SaveChangesAsync();
        }
        return item.Token;

    }
    private WXDbContext getdb() => _ServiceProvider.CreateScope().ServiceProvider.GetRequiredService<WXDbContext>();
}
